/* eslint-disable react/no-danger */
import React, { useState } from 'react';
import { Form, Button, Checkbox, message, ConfigProvider } from 'antd';
import cn from 'classnames';
import { FormContainer } from '@/components/UserForm';
import styles from '../index.less';
import { jsonFormAward } from '../jsonForm';

let initAwardKey = 0;
const Form4 = ({ form, loading, getComponent, entryUser, returnValue, getArrKeys }) => {
    const { getFieldDecorator } = form;
    const [awardKeys, setAwardKeys] = useState([initAwardKey]);
    const [removeAwardIds, setRemoveAwardIds] = useState([]);
    getFieldDecorator('awardKeys', { initialValue: [0] });
    getFieldDecorator('removeAwardIds', { initialValue: [] });

    const [isAgree, setIsAgree] = useState(false);
    getFieldDecorator('awardKeys', { initialValue: [0] }); // 用于保存keys的字段，方便外面可以取之到keys

    const text =
        '<span>本人承诺以上资料真实有效，若有虚假，本人愿接受公司纪律处分并承担一切法律责任。</span><br><span>本人在职期间参与的所有项目及工作内容，均属公司资产。若因离职或其他事由离开公司无权侵犯，因项目及工作内容未结束而离职导致的损失，由本人自行承担经济及法律后果，与公司无关。（点击提交按钮即代表同意此协议)</span>';

    const changeAgree = e => {
        setIsAgree(e.target.checked);
    };

    // eslint-disable-next-line consistent-return
    const addFormList = type => {
        if (type === 'award') {
            const removeId = form.getFieldValue('removeAwardIds');
            const validLength = awardKeys.length - removeId.length;
            if (validLength >= 10) {
                return message.error('至多添加10个');
            }
            initAwardKey += 1;
            awardKeys.push(initAwardKey);
            setAwardKeys([...awardKeys]);
            form.setFieldsValue({
                awardKeys
            });
        }
    };
    // 删除组件
    const deleteGroup = (type, targetKey, deleteId) => {
        let newKeys = [];
        if (type === 'award') {
            if (deleteId) {
                const removeId = [...removeAwardIds, deleteId];
                setRemoveAwardIds(removeId);
                form.setFieldsValue({
                    removeAwardIds: removeId
                });
                return;
            }
            newKeys = awardKeys.filter(key => key !== targetKey);
            setAwardKeys([...newKeys]);
            form.setFieldsValue({
                awardKeys: newKeys
            });
        }
    };
    // 渲染表单组件
    const renderFormItem = type => {
        let arr = [];
        let keys = [];
        let value = [];
        let removeIds = [];
        if (type === 'award') {
            arr = jsonFormAward;
            keys = awardKeys;
            value = entryUser.awardDTOList || [];
            removeIds = removeAwardIds;
        }

        return keys
            .filter(key => !removeIds.includes(value[key] && value[key].id))
            .map(key => (
                <div className={styles.block} key={type + key}>
                    {key !== 0 ? (
                        <i
                            className={cn(styles.del, 'iconfont icongms_list_icon_fail_default')}
                            onClick={() => {
                                deleteGroup(type, key, value[key] && value[key].id);
                            }}
                        />
                    ) : (
                        ''
                    )}
                    <FormContainer>
                        {arr.map(list => (
                            <Form.Item label={list.label} key={list.fileName}>
                                {getFieldDecorator(`${list.fileName}_${key}`, {
                                    rules: list.rules,
                                    initialValue: value[key] && returnValue(list.fileName, value[key])
                                })(
                                    getComponent(
                                        list.type,
                                        list.code,
                                        `${list.fileName}_${key}`,
                                        list.placeholder,
                                        value[key] && value[key].areaCode
                                    )
                                )}
                            </Form.Item>
                        ))}
                    </FormContainer>
                </div>
            ));
    };
    React.useEffect(() => {
        if (entryUser.awardDTOList && entryUser.awardDTOList.length) {
            initAwardKey = entryUser.awardDTOList.length > 0 ? entryUser.awardDTOList.length - 1 : 0;
            setAwardKeys(getArrKeys(entryUser.awardDTOList));
            form.setFieldsValue({
                awardKeys: getArrKeys(entryUser.awardDTOList)
            });
        }
    }, [entryUser]);
    return (
        <ConfigProvider getPopupContainer={trigger => trigger.parentNode}>
            <div className="family">
                <div className={styles.title} id="form4-1">
                    获奖记录
                </div>
                {renderFormItem('award')}
                <div
                    className={styles.add}
                    onClick={() => {
                        addFormList('award');
                    }}
                >
                    +添加获奖记录
                </div>
            </div>
            <Form.Item vvspan={24} labelCol={{ span: 0 }} wrapperCol={{ span: 24 }}>
                {getFieldDecorator('agree', {
                    initialValue: isAgree
                })(
                    <div className={styles.agreeContent}>
                        <Checkbox onChange={changeAgree} style={{ lineHeight: '20px' }} />
                        <div className={styles.text} dangerouslySetInnerHTML={{ __html: text }} />
                    </div>
                )}
            </Form.Item>
            <div className={styles.btnItem}>
                <Button
                    type="primary"
                    htmlType="submit"
                    disabled={!isAgree}
                    loading={
                        loading.effects['user/fetchUpdate'] ||
                        loading.effects['user/updateemployeeavatar'] ||
                        loading.effects['user/uploademployeeavatar']
                    }
                >
                    提交
                </Button>
            </div>
        </ConfigProvider>
    );
};
export default Form4;
